package com.abe.basic.android.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.abe.basic.R;
import com.abe.basic.android.CommonWebActivity;
import com.abe.basic.android.LoginActivity;
import com.abe.basic.android.common.CollectContract;
import com.abe.basic.android.common.CommonContract;
import com.abe.basic.android.common.presenter.CollectArticlePresenter;
import com.abe.basic.android.common.presenter.MainPresenter;
import com.abe.basic.model.http.HttpArticleEntity;
import com.abe.basic.model.http.HttpBannerEntity;
import com.abe.basic.model.http.HttpCollectArticleEntity;
import com.abe.basic.model.http.HttpFriendLinkEntity;
import com.abe.basic.model.http.HttpPageEntity;
import com.abe.basic.model.http.HttpUserEntity;
import com.abe.basic.model.local.HomeArticleEntity;
import com.abe.basic.utils.ConstantBasic;
import com.abe.basic.utils.NormalUtils;
import com.abe.gcore.base.DaggerBaseFragment;
import com.abe.gcore.utils.CoreNormalUtils;
import com.abe.gcore.utils.SPUtils;
import com.abe.gcore.utils.ScreenUtils;
import com.bumptech.glide.Glide;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGABanner;

public class HomeFragment extends DaggerBaseFragment<CommonContract.MainView, MainPresenter> implements SwipeRefreshLayout.OnRefreshListener, SwipeMenuRecyclerView.LoadMoreListener, CommonContract.MainView, CollectContract.CollectArticleView {

    @BindView(R.id.item_rv)
    SwipeMenuRecyclerView itemRv;
    @BindView(R.id.item_swipe_layout)
    SwipeRefreshLayout itemSwipeLayout;

    private CommonAdapter articleAdapter;
    private View headerView;
    private BGABanner bgaBanner;

    private List<HomeArticleEntity> articleEntities;
    private HttpPageEntity<HttpArticleEntity> pageEntity;

    @Inject
    SPUtils spUtils;
    @Inject
    Context context;
    @Inject
    CollectArticlePresenter collectArticlePresenter;

    private LocalReceiver localReceiver;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.item_view_common_recyclerview_swipemenu;
    }

    @Override
    protected void initDatas() {
        localReceiver = new LocalReceiver();
        LocalBroadcastManager.getInstance(context).registerReceiver(localReceiver, new IntentFilter(ConstantBasic.ABE_BASIC_USERENTITY_UPDATE));
        articleEntities = new ArrayList<>();
        articleAdapter = new CommonAdapter<HomeArticleEntity>(getContext(), R.layout.item_list_home_article, articleEntities) {
            @Override
            protected void convert(ViewHolder holder, final HomeArticleEntity articleEntity, final int position) {
                HttpArticleEntity httpArticleEntity = articleEntity.getArticleEntity();
                holder.setText(R.id.item_name, httpArticleEntity.getTitle());
                String sortInfo =
                        TextUtils.isEmpty(httpArticleEntity.getSuperChapterName())
                                ? httpArticleEntity.getChapterName()
                                : httpArticleEntity.getSuperChapterName() + "/" + httpArticleEntity.getChapterName();
                sortInfo = TextUtils.isEmpty(sortInfo) ? "" : "分类：" + sortInfo;
                holder.setText(R.id.item_sort, sortInfo);
                holder.setText(R.id.item_author, httpArticleEntity.getAuthor());
                holder.setText(R.id.item_time, httpArticleEntity.getNiceDate());
                int res = (spUtils.getBoolean(ConstantBasic.STATUS_LOGIN, false)) ?
                        (articleEntity.getCollect() ? R.drawable.icon_collection_1 : R.drawable.icon_collection_0) :
                        R.drawable.icon_collection_0;
                holder.getView(R.id.item_image_collect).setBackgroundResource(res);
                holder.setOnClickListener(R.id.item_image_collect, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //判断登陆
                        boolean isLogin = spUtils.getBoolean(ConstantBasic.STATUS_LOGIN, false);
                        if (!isLogin) {
                            goToActivity(LoginActivity.class);
                        } else {
                            updateCollect(position - 1);
                        }
                    }
                });
            }
        };
        initRV();
        initHeaderView();
        itemRv.addHeaderView(headerView);
        mPresenter.getBanner();
        itemSwipeLayout.setRefreshing(false);
        // 第一次加载数据：一定要调用这个方法，否则不会触发加载更多。
        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
        itemRv.loadMoreFinish(false, true);
        mPresenter.getArticleByPage(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (spUtils.getBoolean(ConstantBasic.STATUS_LOGIN, false)) netUpdateCollect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(context).unregisterReceiver(localReceiver);
    }

    private void initRV() {
        itemSwipeLayout.setOnRefreshListener(this); // 刷新监听。
        itemRv.setLayoutManager(new LinearLayoutManager(getContext()));
        itemRv.addItemDecoration(new DefaultItemDecoration(CoreNormalUtils.getColor(R.color.transparent)));
        itemRv.useDefaultLoadMore(); // 使用默认的加载更多的View。
        itemRv.setLoadMoreListener(this);
        itemRv.setAdapter(articleAdapter);
        articleAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                HttpArticleEntity articleEntity = articleEntities.get(position - 1).getArticleEntity();
                HashMap<String, Object> map = new HashMap<>();
                map.put("url", articleEntity.getLink());
                map.put("name", articleEntity.getTitle());
                goToActivity(CommonWebActivity.class, map);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void initHeaderView() {
        headerView = LayoutInflater.from(getContext()).inflate(R.layout.item_view_bga_banner, itemRv, false);
        bgaBanner = headerView.findViewById(R.id.item_banner);
        //9：5宽高
        int sw = ScreenUtils.getScreenWidth();
        int sh = (sw * 5) / 9;
        bgaBanner.setLayoutParams(new LinearLayout.LayoutParams(sw, sh));
        bgaBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(getActivity())
                        .load(model)
                        .placeholder(R.color.darkgray)
                        .error(R.color.darkgray)
                        .centerCrop()
                        .dontAnimate()
                        .into(itemView);
            }
        });
    }

    private void netUpdateCollect() {
        CoreNormalUtils.sendBroadcast(ConstantBasic.ABE_BASIC_AUTO_LOGIN);
    }

    private void updateCollect(int pos) {
        HomeArticleEntity articleEntity = articleEntities.get(pos);
        Boolean isCollect = articleEntity.getCollect();
        if (isCollect) {
            collectArticlePresenter.unCollectIn(articleEntity.getArticleEntity().getId());
        } else {
            collectArticlePresenter.collectIn(articleEntity.getArticleEntity().getId());
        }
        articleEntity.setCollect(!isCollect);
        articleEntities.set(pos, articleEntity);
        refreshRV();
    }

    private void checkCollect() {
        HttpUserEntity userEntity = NormalUtils.getUser(spUtils);
        for (int i = 0; i < articleEntities.size(); i++) {
            HomeArticleEntity homeArticleEntity = articleEntities.get(i);
            HttpArticleEntity articleEntity = homeArticleEntity.getArticleEntity();
            boolean isCollect = false;
            for (int j = 0; j < userEntity.getCollectIds().size(); j++) {
                Integer id = userEntity.getCollectIds().get(j);
                if (id == articleEntity.getId()) {
                    isCollect = true;
                    break;
                }
            }
            homeArticleEntity.setCollect(isCollect);
            articleEntities.set(i, homeArticleEntity);
        }
    }

    @Override
    public void onRefresh() {
        mPresenter.getBanner();
        mPresenter.getArticleByPage(0);
    }

    @Override
    public void onLoadMore() {
        mPresenter.getArticleByPage(pageEntity.getCurPage());
    }

    @Override
    public void onGetBanner(List<HttpBannerEntity> entities) {
        if (entities == null) return;
        List<String> images = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (HttpBannerEntity entity : entities) {
            images.add(entity.getImagePath());
            names.add(entity.getTitle());
        }
        bgaBanner.setData(images, names);
    }

    @Override
    public void onGetArticles(HttpPageEntity<HttpArticleEntity> entity) {
        if (entity == null) {
            itemRv.loadMoreError(0, "请求失败");
            return;
        }
        pageEntity = entity;
        if (entity.getCurPage() - 1 == 0) {
            articleEntities.clear();
        } else {
            // 数据完更多数据，一定要调用这个方法。
            // 第一个参数：表示此次数据是否为空。
            // 第二个参数：表示是否还有更多数据。
            itemRv.loadMoreFinish(false, true);
        }
        if (entity.getDatas().size() <= 0) {
            itemRv.loadMoreError(0, "没有更多了");
            return;
        }
        for (int i = 0; i < entity.getDatas().size(); i++) {
            HomeArticleEntity homeArticleEntity = new HomeArticleEntity();
            homeArticleEntity.setArticleEntity(entity.getDatas().get(i));
            homeArticleEntity.setCollect(false);
            articleEntities.add(homeArticleEntity);
        }
        if (spUtils.getBoolean(ConstantBasic.STATUS_LOGIN, false)) checkCollect();
        refreshRV();
    }

    private void refreshRV() {
        itemRv.post(new Runnable() {
            @Override
            public void run() {
                articleAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onGetFriendLink(List<HttpFriendLinkEntity> entities) {

    }

    @Override
    public void onGetCollectArticles(HttpPageEntity<HttpCollectArticleEntity> pageEntity) {

    }

    @Override
    public void onRequest(String type, boolean isSucc) {

    }


    @Override
    public void onFinish(String type) {
        itemSwipeLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(int Type, String message) {

    }

    @Override
    public void onFaild(String type) {

    }

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action) && action.equals(ConstantBasic.ABE_BASIC_USERENTITY_UPDATE)) {
                checkCollect();
                refreshRV();
            }
        }
    }
}
